#!/usr/bin/env python3
# 容器内运行：读取本地长文（.txt / .md）-> 作为 context 注入 -> 生成播客（Piper）
# 用法（容器内）：
#   ./scripts/docker_C_doc.py --doc data/knowledge/胜讯2025财报.md \
#                             --topic "胜讯2025财报：亮点、风险与趋势" \
#                             --roles configs/roles_piper.yaml --minutes 4 \
#                             --outdir output_C

import argparse, os, io, sys, yaml
# ---- 关键：把 src/ 放进 sys.path ----
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJ_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
SRC_DIR = os.path.join(PROJ_ROOT, "src")
if SRC_DIR not in sys.path:
    sys.path.insert(0, SRC_DIR)

from llm_client import LLMClient, Role
from tts_client import TTSClient, Speaker
from audio_utils import concat_wavs_ffmpeg, to_mp3_ffmpeg

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--doc", required=True)
    ap.add_argument("--topic", required=True)
    ap.add_argument("--roles", default="configs/roles_piper.yaml")
    ap.add_argument("--minutes", type=int, default=4)
    ap.add_argument("--outdir", default="output_C")
    args = ap.parse_args()

    os.makedirs(args.outdir, exist_ok=True)

    with io.open(args.doc, "r", encoding="utf-8") as f:
        context = f.read()[:12000]

    cfg = yaml.safe_load(open(args.roles,"r",encoding="utf-8"))
    roles = [Role(r["name"], r.get("style","")) for r in cfg["roles"]]
    spks = [Speaker(name=r["name"], backend="piper",
                    model_path=r.get("model_path"),
                    config_path=r.get("config_path"),
                    sample_rate=int(r.get("sample_rate",22050)),
                    sentence_silence=float(r.get("sentence_silence",0.5)),
                    tts_params=r.get("tts") or {}) for r in cfg["roles"]]

    client = LLMClient()
    script = client.generate_dialogue(topic=args.topic, roles=roles,
                                      minutes=args.minutes, mode="deep",
                                      context=context)

    with open(os.path.join(args.outdir,"script.txt"),"w",encoding="utf-8") as f:
        f.write(script)

    tts = TTSClient(spks, os.path.join(args.outdir,"tts"))
    segs = tts.synthesize_dialogue(script, os.path.join(args.outdir,"tts"))
    wav = concat_wavs_ffmpeg(segs, os.path.join(args.outdir,"podcast.wav"))
    mp3 = to_mp3_ffmpeg(wav, os.path.join(args.outdir,"podcast.mp3"))
    print("[OK] 长文播客：", wav, mp3)

if __name__ == "__main__":
    main()
